import {pad} from './filters'

/**
 * 计时器
 * @param duration 时间差（毫秒）
 * @param cb 回调
 */
export function timer (duration, cb) {

  tick()
  var timer = setInterval(tick, 1000)

  function tick () {
    duration -= 1000
    if (duration <= 0) {
      clearInterval(timer)
    }
    cb(transform(duration))
  }

  return timer
}

function transform (millis) {
  return {
    d: Math.floor(millis / 1000 / 60 / 60 / 24),
    h: Math.floor(millis / 1000 / 60 / 60 % 24),
    m: Math.floor(millis / 1000 / 60 % 60),
    s: Math.floor(millis / 1000 % 60),
    t: millis  // total
  }
}

export function stringify ({d, h, m, s}) {
  var str = pad(Math.max(m, 0)) + '分' + pad(Math.max(s, 0)) + '秒'
  if (h > 0) {
    str = pad(h) + '时' + str
  }
  if (d > 0) {
    str = pad(d) + '天' + str
  }
  return str
}

